package com.dllo.lanou.cookapp.activity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.dllo.lanou.cookapp.R;
import com.dllo.lanou.cookapp.entity.Post;
import com.dllo.lanou.cookapp.entity.User;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadFileListener;

public class ShowCookActivity extends AppCompatActivity implements View.OnClickListener {
    private List<String> imgs;
    @Bind(R.id.add_ims)
    ImageView add_img;
    @Bind(R.id.tv_send)
    TextView tv_send;
    private int count =0;
    @Bind(R.id.post_content)
    EditText post_content;
    String content;
    private Handler handler;
      Post  post = new Post();

    private String pathImage;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_cook);

        ButterKnife.bind(this);

        tv_send.setOnClickListener(this);
        add_img.setOnClickListener(this);
          handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);

        if (msg.what == 0) {
            String urls = (String) msg.obj;
            User user = BmobUser.getCurrentUser(ShowCookActivity.this, User.class);
            post.setContent(content);
            post.setAuthor(user);
            post.setImgsUrl(urls);
            post.save(ShowCookActivity.this, new SaveListener() {
                @Override
                public void onSuccess() {
                    //添加成功
                    Log.i("添加动态信息", "添加动态信息成功");

                    Intent intent = new Intent();
                    intent.putExtra("post", post);
                    setResult(101, intent);
                    finish();
                }

                @Override
                public void onFailure(int i, String s) {
                    Log.i("添加动态信息", "添加动态信息失败");
                }
            });
        }

           }
};



    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_send:
                content = post_content.getText().toString();
                if (pathImage != null ) {

                    final BmobFile bmobFile = new BmobFile(new File(pathImage));
                    bmobFile.uploadblock(this, new UploadFileListener() {

                        @Override
                        public void onSuccess() {
                            // TODO Auto-generated method stub
                            //bmobFile.getUrl()---返回的上传文件的地址（不带域名）
                            //bmobFile.getFileUrl(context)--返回的上传文件的完整地址（带域名）
                            //toast("上传文件成功:" + bmobFile.getFileUrl(context));

                            Message message = new Message();
                            message.what = 0;
                            message.obj = bmobFile.getFileUrl(ShowCookActivity.this);
                            handler.sendMessage(message);

                        }

                        @Override
                        public void onProgress(Integer value) {
                            // TODO Auto-generated method stub
                            // 返回的上传进度（百分比）
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            // TODO Auto-generated method stub
                          //  toast("上传文件失败：" + msg);
                        }
                    });


                }
                break;

            case R.id.add_ims:
                Log.i("Ssssssss","sss");
                Intent intent_icon = new Intent(Intent.ACTION_PICK, null);
                intent_icon.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent_icon, 100);

                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){

            case 100:


                Uri uri = data.getData();

                try {
                    Bitmap bm = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);

                    add_img.setImageBitmap(bm);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (!TextUtils.isEmpty(uri.getAuthority())) {
                    //查询选择图片
                    Cursor cursor = getContentResolver().query(
                            uri,
                            new String[] { MediaStore.Images.Media.DATA },
                            null,
                            null,
                            null);
                    //返回 没找到选择图片
                    if (null == cursor) {
                        return;
                    }
                    //光标移动至开头 获取图片路径
                    cursor.moveToFirst();
                    pathImage = cursor.getString(cursor
                            .getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();



                }
        }

    }

    private Bitmap compressBmpFromBmp(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int options = 100;
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        while (baos.toByteArray().length / 1024 > 100) {
            baos.reset();
            options -= 10;
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
        return bitmap;
    }





}
